package com.cheetah.handler;

import com.cheetah.annotation.Handler;
import com.cheetah.protocol.Heartbeat;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author Administrator
 * @Date 2019/7/31
 * @Version V1.0
 * @Description:
 **/
@Component
@Slf4j
@Handler(sharable = true,order = 999)
@ChannelHandler.Sharable
public class HeartBeatServerHandler extends SimpleChannelInboundHandler<Heartbeat> {

    private int loss_connect_time = 0;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                loss_connect_time++;
                if (loss_connect_time > 2) {
                    ctx.channel().close();
                }
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

//    @Override
//    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        log.error(cause.getMessage(),cause);
//        ctx.close();
//    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Heartbeat msg) throws Exception {
        Heartbeat hb = Heartbeat.builder()
                .cmd("pong")
                .build();
        ctx.writeAndFlush(hb);
        log.info("server receive ping from {}",ctx.channel().remoteAddress());
        log.info("server response pong! {}", new Date());
    }
}
